/**
 * @Author: ls <ls-mac>
 * @Date:   2019-08-13 17:59:48
 * @Last modified by:   ls-mac
 * @Last modified time: 2020-03-08 22:48:52
 */
import { packageAddOrEdit } from 'services/package';
import { extraItemRelation } from 'services/extraItem';

import { orderPage, orderCreate } from 'services/order';

export default {
  namespace: 'orderCommit',
  state: {
    data: {
      list: [],
      pagination: {},
    },
    extraItemList: [],
    expandedRowKeys: [],
  },

  effects: {
    *fetch({ payload, callback }, { call, put }) {
      const response = yield call(orderPage, payload);
      yield put({
        type: 'saveList',
        payload: response,
      });
    },
    *clearExtraItemList({ payload, callback }, { call, put }) {
      yield put({
        type: 'saveclearExtraItemList',
      });
      if (callback) {
        callback();
      }
    },
    *packageAddOrEdit({ payload, callback }, { call, put }) {
      const response = yield call(packageAddOrEdit, payload);
      if (callback) {
        callback(response);
      }
    },
    *create({ payload, callback }, { call, put }) {
      const response = yield call(orderCreate, payload);
      if (callback) {
        callback(response);
      }
    },

    *extraItemRelation({ payload, callback }, { call, put }) {
      debugger;
      const response = yield call(extraItemRelation, payload);
      yield put({
        type: 'saveExtraItemList',
        payload: response,
      });
      if (callback) {
        callback(response);
      }
    },
  },

  reducers: {
    saveList(state, action) {
      const {
        data: { orderList, pageIndex, pageSize, recordCount },
      } = action.payload;

      if (!(orderList instanceof Array)) {
        return;
      }

      const newList = orderList.map(val => {
        const v = val;
        v.key = `k${v.id}`;
        return v;
      });

      return {
        ...state,
        data: {
          list: newList,
          pagination: {
            current: pageIndex,
            total: recordCount,
            pageSize,
          },
        },
      };
    },

    saveExtraItemList(state, action) {
      const { data } = action.payload;

      if (!data) {
        return {
          ...state,
        };
      }

      const newList = data.map(val => {
        const v = val;
        v.key = `k${v.id}`;
        // if (!v.extraItemDetailList) {
        //   v.extraItemDetailList = [{ ...v, id: `k${v.id}`, extraItemId: v.id, isClone: true }];
        // }
        return v;
      });

      const newList2 = data.map(val => {
        const v = val;
        return `k${v.id}`;
      });

      return {
        ...state,
        extraItemList: newList,
        expandedRowKeys: newList2,
      };
    },
    saveclearExtraItemList(state, action) {
      return {
        ...state,
        extraItemList: [],
      };
    },
  },
};
